package com.chenwb.concurrency.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ReenterLockTryLock implements Runnable {

	ReentrantLock reenteantLock = new ReentrantLock();

	/**
	 * 执行
	 */
	@Override
	public void run() {
		try {
			System.out.println(System.currentTimeMillis()/1000 + " " + Thread.currentThread().getName() + " wait lock");
			if(reenteantLock.tryLock(5, TimeUnit.SECONDS)) {
				Thread.sleep(6000);
				System.out.println(System.currentTimeMillis()/1000 + " " +Thread.currentThread().getName() + " done");
			} else {
				System.out.println(System.currentTimeMillis()/1000 + " " +Thread.currentThread().getName() + " get lock failed");
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			if (reenteantLock.isHeldByCurrentThread()) {
				reenteantLock.unlock();
				System.out.println(System.currentTimeMillis()/1000 + " " +Thread.currentThread().getName() + " unlock");
			}
		}
	}

	/**
	 * 执行结果
	 * 1585795251 thread1 wait lock
	 * 1585795251 thread2 wait lock
	 * 1585795256 thread2 get lock failed
	 * 1585795257 thread1 done
	 * 1585795257 thread1 unlock
	 * thread1执行成功，thread2等待5s后还没有获取锁，trylock则返回false
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		ReenterLockTryLock thread = new ReenterLockTryLock();
		Thread t1 = new Thread(thread, "thread1");
		Thread t2 = new Thread(thread, "thread2");
		t1.start();
		t2.start();
	}
}
